﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sunny.UI;

namespace SmartMotion.Core.Tools
{
    public class WhileItem : ActionExpression
    {
        public override ActionResult Run()
        {
            Stopwatch sw = Stopwatch.StartNew();
            State = "...";

            Em.GetEvent<RunActionItem>().Publish(this);
            IniState(Nodes);
            Em.GetEvent<DebugMessage>().Publish($"运行{Name}");
            ActionResult result;
            while (true)
            {
                continueLab:
                result = RunMethod();//运行while的表达式
                if (!BoolResult)//如果结果为false,退出循环,不会执行子节点
                {
                    break;
                }
                if (result == ActionResult.Success)//while表达式没异常
                {
                    foreach (ActionItem actionItem in Nodes)//执行while内的节点
                    {
                        result = actionItem.Run();
                        switch (result)
                        {
                            case ActionResult.Continue:
                                goto continueLab;
                            case ActionResult.Break:
                            case ActionResult.Error:
                                goto breakLab;
                        }
                    }
                }
            }
            breakLab:

            State = result.ToString();
            Time = (int)sw.ElapsedMilliseconds;
            Em.GetEvent<RunActionItem>().Publish(this);
            return result;
        }
    }

    public class ContinueItem : ActionItem
    {
        protected override ActionResult RunMethod()
        {
            return ActionResult.Continue;
        }

        public override UIPage GetParasPage()
        {
            return null;
        }
    }

    public class BreakItem : ActionItem
    {
        protected override ActionResult RunMethod()
        {
         
            return ActionResult.Break;
        }

        public override UIPage GetParasPage()
        {
            return null;
        }   
    }

}
